/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * Author: zhaosj
 * Date: 2011-9-7 下午18:17:25
 */
package com.swing.excelplugins.listener;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.swing.excelplugins.panel.MainPanel;

/**
 * 
 * @author zhaosj
 * 
 */
public class TradePanelListener extends MouseAdapter {

	private MainPanel panel = null;

	/**
	 * 点击按钮触发事件
	 */
	@Override
	public void mouseClicked(MouseEvent e) {

		if (e.getButton() == 1) {

			String ip = panel.getFieldIp().getText();
			String port = panel.getFieldPort().getText();
			String filePath = panel.getFieldFilePath().getText();

			getRemoteData(ip + ":" + port, filePath);

			System.out.println(filePath);
			System.out.println(ip);

		}

		System.exit(0);
	}

	/**
	 * 获取远程XML内容写入到本地文件中
	 * 
	 * @param remoteUrl
	 * @param filePath
	 */
	private void getRemoteData(String remoteIp, String filePath) {

		String fileName = filePath + "\\MSSoapInit.xml";
		String remoteUrl = "http://" + remoteIp + "/ccxe/services/ccxWebService?wsdl";

		try {
			URL url = new URL(remoteUrl);
			URLConnection con = url.openConnection();

			// 从远程连接获取输入流
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

			// 输出到文件
			FileOutputStream os = new FileOutputStream(fileName, false);

			String line = null;
			while ((line = in.readLine()) != null) {

				line = replaceSoapAddress(line, remoteIp);
				os.write((line + "\r\n").getBytes());
				os.flush();
			}

			// 写完收工
			os.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public String replaceSoapAddress(String str, String newIp) {
		if (str.contains(":address")) {
			String ipStr = str.split("http://")[1];
			String ip = ipStr.substring(0, ipStr.indexOf("/"));
			str = str.replaceAll(ip, newIp);
		}

		return str;
	}

	public void setPanel(MainPanel panel) {
		this.panel = panel;
	}

}
